package run.bottle.app.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import run.bottle.app.exception.NotFoundException;
import run.bottle.app.model.entity.SysUser;
import run.bottle.app.repository.UserRepository;
import run.bottle.app.service.UserService;
import run.bottle.app.service.base.AbstractCrudService;

import java.util.Optional;

/**
 * UserService implementation class.
 *
 * @author Lycheng
 */
@Service
public class UserServiceImpl  extends AbstractCrudService<SysUser, Integer> implements UserService {

    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository, UserRepository userRepository1) {
        super(userRepository);
        this.userRepository = userRepository1;
    }

    @Override
    public Optional<SysUser> getByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public SysUser getByUsernameOfNonNull(String username) {
        return getByUsername(username).orElseThrow(() -> new NotFoundException("The username does not exist").setErrorData(username));
    }

    @Override
    public Optional<SysUser> getByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    @Override
    public SysUser getByEmailOfNonNull(String email) {
        return getByEmail(email).orElseThrow(() -> new NotFoundException("The email does not exist").setErrorData(email));
    }

    @Override
    public boolean passwordMatch(SysUser user, String plainPassword) {
        return !StringUtils.isEmpty(plainPassword) && BCrypt.checkpw(plainPassword, user.getPassword());
    }
}
